﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LPrisaMVC.Entities;
using System.Data;

namespace LPrisaMVC.DAO
{
    public class ProveedorDAO: MasterRepository,IProveedorDAO
    {
        public List<PROVEEDOR> GetAllFromProveedor()
        {
            var query = from c in Context.PROVEEDORs
                        select c;
            return query.ToList();
        }

        public List<PROVEEDOR> GetFromProveedorByDescripcion(string descripcion)
        {
            if (descripcion != "")
            {
                var query = from c in Context.PROVEEDORs
                            where c.RazonSocial.ToUpper().Contains(descripcion.ToUpper()) || c.Ruc.ToUpper().Contains(descripcion.ToUpper())
                            select c;
                return query.ToList();
            }
            else
            {
                var query1 = from c in Context.PROVEEDORs
                             select c;
                return query1.ToList();
            }
        }

        public PROVEEDOR GetFromProveedorByRuc(string id)
        {
            var query = from c in Context.PROVEEDORs
                        where c.Ruc.Equals(id)
                        select c;

            return query.SingleOrDefault();
        }

        public void AddProveedor(PROVEEDOR proveedor)
        {
            Context.PROVEEDORs.Add(proveedor);
            Context.SaveChanges();
        }

        public void UpdateProveedor(PROVEEDOR proveedor)
        {
            Context.PROVEEDORs.Attach(proveedor);
            Context.Entry(proveedor).State = EntityState.Modified;
            Context.SaveChanges();
        }

        public void RemoveProveedor(int id)
        {
            var existe = Context.PROVEEDORs.Find(id);
            Context.PROVEEDORs.Remove(existe);
            Context.SaveChanges();
        }

        public bool ExistDuplicidadRucRazonSocial(string ruc, string razonSocial, int id)
        {
            var query = from c in Context.PROVEEDORs
                        where (c.Ruc.ToUpper().CompareTo(ruc.ToUpper()) == 0 || c.RazonSocial.ToUpper().CompareTo(razonSocial.ToUpper()) == 0)
                        && c.Id != id
                        select c;

            return query.Any();
        }


        public PROVEEDOR GetFromProveedorById(int id)
        {
            var query = from p in Context.PROVEEDORs
                        where p.Id.Equals(id)
                        select p;
            return query.SingleOrDefault();
        }
    }
}
